<template>
  <div class="search-container">
    <form class="search-from" action="/">
    <van-search
    v-model="searchText"
    show-action
    placeholder="请输入搜索关键词"
    background="#3296fa"
    @search="onSearch"
    @cancel="onCancel"
    @focus="isshow=false"
  />
</form>

<!-- 搜索结果 -->
<result v-if="isshow" :searchText="searchText"></result>
<!-- 搜索结果 -->

<!-- 推荐列表 -->
<suggestion :searchText="searchText" v-else-if="searchText" @search="onSearch"></suggestion>
<!-- 推荐列表 -->

<!-- 历史记录 -->
<history v-else :historylist="historylist" @del="historylist=[]"  @search="onSearch"></history>
<!-- 历史记录 -->

  </div>
</template>
<!-- 搜索框获得焦点，显示历史记录组件 
获取搜索框的值，使isshow等于true 显示搜索结果组件
监听搜索框变化，显示推荐列表的组件
默认显示历史记录组件 -->

<script>
import suggestion from './components/search-suggestion.vue'
import result from './components/search-result.vue'
import history from './components/search-history.vue'
import {getItem,setItem} from '@/utils/storage.js'
export default {
  data(){
    return{
      searchText:'',
      isshow:false,
      historylist:getItem('TT-SEARCH-HISTORYS') || [],
    }
  },
  methods:{
    onSearch(val){
      if(val === '') return
    this.searchText =val
    const index =this.historylist.indexOf(val)
    if(index !== -1){
      this.historylist.splice(index,1)
    }
    this.historylist.unshift(val)
    this.isshow =true
    },
    onCancel(){
      this.$router.back()
    }
  },
  watch:{
    historylist(value){
    setItem('TT-SEARCH-HISTORYS',value)
    }
  },
  components:{history,result,suggestion}
}
</script>

<style scoped lang="less">
 .search-container{
  padding-top: 108px;
  .van-search__action{
    color: #fff;
  }
  .search-from{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 222;
  }
} 

</style>